Vue.component('multi-menu',{ 
	data(){
		  return {
			  iconWidth:'20px',
			  iconHeight:'20px'
			  
		  }
	  },
        props:['dropDownData','collapsed'],
        template:'\
            <div >  \
             <template v-for="(item,index) in dropDownData">\
             <el-submenu v-if="item.children && item.children.length > 0" :index="item.id" :key="item.id"">\
               <span @click="childrenClick(item)" slot="title">\
	        	<label style="margin:0px 0 0 0;width:20px;height:20px;" :style="{background:changeUrl(item)}"></label>\
        		<span v-show="!collapsed">{{item.name}}</span></span> \
               <multi-menu :drop-down-data="item.children"></multi-menu>\
             </el-submenu>\
              <el-menu-item v-else :index="item.id" :key="item.id" @click="childrenClick(item)" >\
        		<span @dblclick="menuDoubleClick(item)"><label style="margin:0px 0 0 0;width:20px;height:20px;" :style="{background:changeUrl(item),backgroundImage:changeUrl(item)}"></label>\
        		{{item.name}}</span></el-menu-item>\
              </template>\
            </div>',
  methods: {
   childrenClick:function(item){
	   app.$options.methods.menuItemChildrenClick(item);
   },
 
   changeUrl:function(url){
	   var url = url.icon;
	   if(url && url !='' && url != null){
			 if(url.startsWith('url(skin')){
				return url.replace('skin>',"/"+projectName+'/dorado/client/skins/coral-reef/');
			 }else if(url.startsWith('url(>skin')){
				return url.replace('>skin>',"/"+projectName+'/dorado/client/skins/coral-reef/');
			 }else if(url.startsWith('dorado')){
				return "url(/"+projectName+"/"+ url + ")";
			 }
		}
		return url;
   },
   menuDoubleClick:function(item){
   	 app.$options.methods.menuDoubleClick(item);
     }
    } 
  })
  Vue.prototype.$projectName = projectName;
var app = new Vue({
	el: "#app",
	data: {
		menus:[],
		headMenus:[],
		menuVisible:false,
		activeName:"1",//当前高亮显示的tab下标
		logout_dilaogVisible:false,
		mdf_dilaogVisible:false,
		editableTabs:[{
			id:'1',
			title:"我的工作台",
			name:"1",
			path:"./workbeach",
			content:"<iframe src='./workbench' style='height:100%;width:100%' frameborder='0'> </iframe>"
		}],
		rightClickTabIndex:"",
		tabIndex:"1",
		collapsed:false,
		modifyPwdWidth:'40%',
		logoutWidth:'30%',
		elColLeft:22,
		elColRight:2,
		passwordForm:{
			oldPassword:'',
			newPassword:'',
			okNewPassword:'',
		},
		rules1:{
			oldPassword:[
				{ required:true,message:"原密码不能为空",trigger:'blur' },
				{ validator:function(rule1,value,callback){
					$.ajax({	
						type: "GET",
						url: "./user/validatePassword",
						data: {
							oldPassword: value
						},
						success : function(result) {
							if(!result){
								callback(new Error('原密码输出错误！'));
							}else{
								callback();
							}
						}
					});
				},trigger:'blur'}
				],
			newPassword:[
				{required : true ,message : "新密码不能为空" , trigger : 'blur' },
				{min : 6 , message : "密码长度必须大于6位数" },
				{validator:function(rule1,value,callback){
					var pd2=app.passwordForm.okNewPassword;
					if(pd2===""){
						callback();
					}else{
						if(value!==pd2){
							callback(new Error('两次输入密码不一致！'));
						}else{
							callback();
						}
					}
				},trigger:"blur"}
			],
			okNewPassword:[
				{ required : true , message : "确认新密码不能为空" , trigger : 'blur' },
				{ min : 6, message : "密码长度必须大于6位数" },
				{validator:function(rule1,value,callback){
						var pd1=app.passwordForm.newPassword;
						if(pd1===""){
							callback();
						}else{
							if(value!==pd1){
								callback(new Error('两次输入密码不一致！'));
							}else{
								callback();
							}
						}
					},trigger:"blur"
				}],
		},
		
	},
	mounted: function() {
		var screenWidth= window.screen.width;
		//移动端适配
		if(screenWidth<756){
		   this.collapsed=true
		   this.modifyPwdWidth ="84%"
		 }
		if(screenWidth<321){
		   this.elColRight= 6,
		   this.elColLeft =18
		} else if(screenWidth<769){
		   this.elColRight= 5,
		   this.elColLeft =19
		}
		if(screenWidth<1225){
		   this.logoutWidth ='84%'
		}
		this.getHeadMenuList();
		this.getMenuList("root-bstek");
	},
	computed:{
		activeMenuIndex:function(){
			var tab =this.editableTabs.find(tab => tab.name == this.activeName)
			if(tab){
				return tab.id;
			}else{
				return '';
			}
		     
		}
	},
	methods: {
		changeUrl:function(url){
			if(url && url !='' && url != null && url!='undefied'){
				if(url.startsWith('url(skin')){
					return url.replace('skin>',"/"+projectName+'/dorado/client/skins/coral-reef/');
				}else if(url.startsWith('url(>skin')){
					return url.replace('>skin>',"/"+projectName+'/dorado/client/skins/coral-reef/');
				}else if(url.startsWith('dorado')){
					return "url(/"+projectName+"/"+ url + ")";
				}
			}
			return url;
		},
		rightMenu:function(item){
			  //当前右击的tab的下标
		   this.rightClickTabIndex = item.name
		   this.menuVisible = false // 先把模态框关死，目的是 第二次或者第n次右键鼠标的时候 它默认的是true
           this.menuVisible = true  // 显示模态窗口，跳出自定义菜单栏
           var menu = document.querySelector('#menu')
		   document.addEventListener('click', this.foo) // 给整个document添加监听鼠标事件，点击任何位置执行foo方法
           menu.style.display = "block";
           menu.style.left = event.clientX + 0 + 'px'
           menu.style.top = event.clientY  + 'px'
		
	   },
	   foo:function() { // 取消鼠标监听事件 菜单栏
           this.menuVisible = false
           document.removeEventListener('click', this.foo) // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了

       },
	   closeTabs:function(type){
    	   var tabs=this.editableTabs;//获取所有的tab
    	   var activeIndex;
    	   if(type=='1'){
    		   // 关闭自己
    		   tabs.forEach((tab,index)=>{
    			   if(tab.name===this.rightClickTabIndex){
    				   var nextTab=tabs[index+1] || tabs[index-1];
    				   if(nextTab){
						   this.activeName=nextTab.name;//当前高亮显示的tab 的左边或右边的 下标
    		               this.editableTabs=tabs.filter(tab => tab.name != this.rightClickTabIndex)
						   return false;
    				   }
    			   }
    		   });
    		 
    	   }else if(type=='2'){
    		  // 关闭其他
    		   tabs.forEach((tab,index)=>{
    			   if(tab.name===this.rightClickTabIndex){
    				   activeIndex=this.rightClickTabIndex
					   //path=tab.path//将最后显示的tab的path值赋值给path
    			   }
    		   });
    		   this.activeName=activeIndex;//当前高亮显示的tab 的 下标
    		   this.editableTabs=tabs.filter(tab => tab.name == activeIndex)
    	   }else if(type=='3'){
    		   // 关闭所有
    		   this.activeName='';//当前高亮显示的tab 的 下标
    		   this.editableTabs=tabs.filter(tab => tab.name == null)
    	   }
          },
		getHeadMenuList:function(){
			$.ajax({
				url: "./api/headMenus",
				success: function(result) {
					app.headMenus=result;
				}
			});
		},
		/**
		 *	获取菜单数据
		 */
		getMenuList:function(parentId){
			$.ajax({
				url: "./api/menus",
				data: {
					"parentId": parentId,
				},
				success: function(result) {
					app.menus=result;
				}
			});
		},
		menuDoubleClick:function(item){
			var path=item.path;//点击菜单栏的path
			if(path!=null){
		       path =projectName+"/"+path;
			}
			app.editableTabs.forEach(function(tab){
				if(tab.path==('/'+path)){
					//刷新目标页面
					app.$options.methods.refreshFrame(path);
				}
			});
		},
		/**
		 * 刷新目标页面
		 */
		refreshFrame:function(path){
			var frames =window.frames;
			for(var i=0;i <frames.length;i++){
				if(frames[i].location.pathname=="/"+path){
					frames[i].location.reload();
				}
			}
			
		},
		/**
		 * 一级菜单点击事件
		 */
		menuItemClick:function(menu){
			var path=menu.path;
			
			if(path || path != "" || path != null){
				
			}else{
				return false;
			}
		},
		/**
		 * 二级菜单 点击 添加tab
		 */
		menuItemChildrenClick:function(item){
			var path=item.path;//点击菜单栏的path
			if(path!=null){
		       path =projectName+"/"+path;
			}
			// 判断是否已经打开，如果已经打开，则刷新？
			var flags = false;
			app.editableTabs.forEach(function(tab){
				if(tab.path==('/'+path)){
					// 已经存在
					flags=true;
					//重新激活标签页
					app.activeName = tab.name;
				}
			});
			if(flags){
				
			}else{
				var id = item.id; //菜单栏的id
				var urlName=item.name;//点击菜单栏的name
				var tabs=app.editableTabs;//获取已经存在的tabs数组
				var activeIndex=app.activeName//获取当前高亮的下标
				if (path && path != "" && path != null){
					var	flag = true;
					tabs.forEach(function(tab){
						if(path===tab.path){//如果新增path存在，则高亮显示这个tab
							app.activeName=tab.name;//高亮显示tab的下标;
							flag=false;
						}
						if(activeIndex===tab.name){
							src=tab.path//获取高亮的path
							monitorIndex=tab.name
						}
					});
					if(flag === false){
						return false;
					}
					path = '/' + path;
					var newTabName=++app.tabIndex+'';//标签顺序
					var contentIframe='<iframe src=' +path +' style="height:100%;width:100%" frameborder="0"></iframe>'
					app.editableTabs.push({
						id:id,
						title:urlName,
						name:newTabName,
						path:path,
						content:contentIframe,
						icon:item.icon
					});
					app.activeName=newTabName;
				}else{
					return false;
				}
			}
			
		},
	
		//将iframe的src截取成 './monitor'
		getUrlRelativePath : function(src){
			var arrUrl = src.split("//");
			var start = arrUrl[1].indexOf("/");
			var relUrl = arrUrl[1].substring(start);
			return relUrl.replace("/" + projectName, ".")
		},
		//获取页面上iframe的个数，匹配到地址为./monitor的iframe,然后添加
		addUrl : function(path){
			var length = $("iframe").length
			if (length > 0) {
				for (var i = 0; i < length; i++) {
					var src = $("iframe")[i].src
					src =  app.$options.methods.getUrlRelativePath(src)
					if (src === "./monitor") {
						app.$options.methods.add($("iframe")[i], path);
					} else {
					}
				}
			}
		},
		//拼接添加到./monitor页面
		add : function(iframe, path) {
			// 1.判断div存在的个数
			// 2.设置样式
			// 3.添加元素。
			var num = [];
			var urlArray = [];
			var document = iframe.contentWindow.document;
			var div1 = document.getElementById("div1");
			if (div1) {
				num.push("div1");
				var url1 = document.getElementById("iframe1").contentWindow.location.href;
				url1 = app.$options.methods.getUrlRelativePath(url1)
				urlArray.push(url1);
			}
			var div2 = document.getElementById("div2");
			if (div2) {
				num.push("div2");
				var url2 = document.getElementById("iframe2").contentWindow.location.href;
				url2 = app.$options.methods.getUrlRelativePath(url2);
				urlArray.push(url2);
			}
			var div3 = document.getElementById("div3");
			if (div3) {
				num.push("div3");
				var url3 = document.getElementById("iframe3").contentWindow.location.href;
				url3 = app.$options.methods.getUrlRelativePath(url3);
				urlArray.push(url3);
			}
			var div4 = document.getElementById("div4");
			if (div4) {
				num.push("div4");
				var url4 = document.getElementById("iframe4").contentWindow.location.href;
				url4 = app.$options.methods.getUrlRelativePath(url4);
				urlArray.push(url4);
			}
			if (urlArray.indexOf(path) == -1) { // 判断新增的这个元素的src 与
												// 旧元素的 src
												// 是否相等，相等给提示已存在
				var divNo = '';
				var classNmae = '';
				var divIframeId = '';
				var iframeId = '';
				if (num.length == 0) {
					// num=0表示，全部删除了。则只需给新元素加样式（GridFull） 新 元素的
					// id=div1
					divNo = "div1";
					classNmae = "GridFull";
					divIframeId = "div_iframe1";
					iframeId = "iframe1";
					app.$options.methods.appendHtml(divNo, classNmae,
							iframeId, divIframeId, path, document);
				} else if (num.length == 1) {// num=1表示，只剩一个
					// 改变 旧元素 的样式，新添加的元素也为这个样式（Grid）
					var divNum = num[0];
					var div = document.getElementById("" + divNum
							+ "");
					div.className = "Gird-cell"
					// 添加元素
					classNmae = "Gird-cell";
					var divNum = num[0];
					if (divNum == "div1") {// 存在的元素id=div1
						divNo = 'div2'
						divIframeId = "div_iframe2";
						iframeId = "iframe2";
					} else {
						divNo = 'div1';
						divIframeId = "div_iframe1";
						iframeId = "iframe1";
					}
					app.$options.methods.appendHtml(divNo, classNmae,
							iframeId, divIframeId, path, document);
				} else if (num.length == 2 || num.length == 3) {// num=2表示，只剩2个
					// 添加元素
					classNmae = "Gird-cell"
					if (num.indexOf("div1") == -1) { // 如果num.indexof("div1")==-1说明
														// 数组中
														// 不存在div的Id=div1的，则
														// 我可以新增这个id
						divNo = "div1";
						divIframeId = "div_iframe1";
						iframeId = "iframe1";
					} else if (num.indexOf("div2") == -1) {
						divNo = "div2";
						divIframeId = "div_iframe2";
						iframeId = "iframe2";
					} else if (num.indexOf("div3") == -1) {
						divNo = "div3";
						divIframeId = "div_iframe3";
						iframeId = "iframe3";
					} else {
						divNo = "div4";
						divIframeId = "div_iframe4";
						iframeId = "iframe4";
					}
					app.$options.methods.appendHtml(divNo, classNmae,
							iframeId, divIframeId, path, document);
				} else if (num.length == 4) {
					// 代表没有删除，不添加新元素，给提示
					app.$notify({
						title:'您的窗口数已达到上限，请关闭其中几个再打开!',
						type:'error',
						duration:3000,
						position:'bottom-right'
					})
					return false;
				}
			} else {
				app.$notify({
					title:'此页面已经在显示窗口中打开!',
					type:'error',
					duration:3000,
					position:'bottom-right'
				})
				return false;
			}
		},
		//拼接html
		appendHtml : function(divNo, classNmae, iframeId,
				divIframeId, path, doc) {
			var sHtml = null;
			sHtml = '<div id="' + divNo + '" class="' + classNmae
					+ '">';
			sHtml += '<div style="background: #E0E1E2 none; height: 31px;">';
			sHtml += '<button class="tooltip-test btn  btn-sm" style="float:right" title="删除" onclick="del('
					+ '\'' + divNo + '\'' + ')"> ';
			sHtml += '<span class="glyphicon  glyphicon-remove"></span> </button>';
			sHtml += '<button class="tooltip-test btn  btn-sm" title="放大" onclick="fullScreen('
					+ '\''
					+ iframeId
					+ '\''
					+ ','
					+ '\''
					+ divIframeId
					+ '\''
					+ ')" style="float:right">';
			sHtml += '<span class="glyphicon  glyphicon-resize-full"></span>	</button> </div>';
			sHtml += '<div id="' + divIframeId
					+ '" class="fullScreen">';
			sHtml += '<iframe id="'
					+ iframeId
					+ '" style="height:100%;width:100%" frameborder="0" src="'
					+ path + '"></iframe> </div> </div>';
			var main = doc.getElementById("main");
			$(main).append(sHtml);
		},
		//折叠导航栏
		collapse:function(){
			this.collapsed=!this.collapsed;
		},
		handleOpen(key,keyPath){
		},
		handleClose(key,keyPath){
		},
		/**
		 * 关闭Tab
		 */
		removeTab:function(targetName){
			var tabs=this.editableTabs;//获取所有的tab
			var activeIndex=this.activeName;//获取当前当前高亮的tab的下标或者说是index
			if(activeIndex===targetName){
				tabs.forEach((tab,index)=>{
					if(tab.name===targetName){
						var nextTab=tabs[index+1] || tabs[index-1];
						if(nextTab){
							activeIndex=nextTab.name
							path=nextTab.path//将最后显示的tab的path值赋值给path
						}
					}
				});
			}
			this.activeName=activeIndex;//当前高亮显示的tab 的 下标
			this.editableTabs=tabs.filter(tab => tab.name !== targetName)
		},
		/**
		 * 点击X 关闭修改密码框事件
		 */
		dialogBerforeClose:function(){
			this.$refs.passwordForm.resetFields();//重置数据
			this.mdf_dilaogVisible=false
		},
		/**
		 * 退出
		 */
		logout:function(){
			window.location.href="./logout"
		},
		/**
		 * 关闭
		 */
		closeDialog:function(){
			this.$refs.passwordForm.resetFields();//重置数据
			this.mdf_dilaogVisible=false;
		},
		/**
		 * 判断显示修改密码框还是退出框
		 */
		showDialog:function(param){
			if(param==="out"){
				this.logout_dilaogVisible=true
			}else{
				this.mdf_dilaogVisible=true
			}
		},
		/**
		 * 修改密码
		 */
		updatePassWord:function(form){
			app.$refs.passwordForm.validate((valid) =>{
				if(valid){
					$.ajax({
						data : {
							"newPassword" : form.newPassword
						},
						type : "GET",
						url : "./user/changePassword",
						success : function() {
							app.$notify({
								title:'保存成功！',
								type:'success',
								duration:3000,
								position:'bottom-right'
							})
							window.location.href="/frame/logout";
						}
					});
				}
			});
		},
	}
});
